package drds.global_transaction.api.message_codec.request_and_response.transaction.global_transaction.global_transaction_begin;

import java.nio.ByteBuffer;

import drds.global_transaction.api.api.RpcContext;
import drds.global_transaction.api.message_codec.IMergedMessage;
import drds.global_transaction.api.message_codec.request_and_response.transaction.TransactionResponse;
import drds.global_transaction.api.message_codec.request_and_response.transaction.global_transaction.GlobalTransactionRequestMessage;
import lombok.Getter;
import lombok.Setter;

public class GlobalTransactionBeginRequestMessage extends GlobalTransactionRequestMessage implements IMergedMessage
{

	private static final long serialVersionUID = 1L;

	@Setter
	@Getter
	private int globalTransactionTimeout = 60000;
	@Setter
	@Getter
	private String transactionName;

	@Override
	public short getTypeCode()
	{
		return global_transaction_begin_request_message;
	}

	@Override
	public byte[] encode()
	{
		ByteBuffer byteBuffer = ByteBuffer.allocate(256);
		byteBuffer.putInt(globalTransactionTimeout);

		if (this.transactionName != null)
		{
			byte[] bytes = transactionName.getBytes(UTF8);
			byteBuffer.putShort((short) bytes.length);
			if (bytes.length > 0)
			{
				byteBuffer.put(bytes);
			}
		} else
		{
			byteBuffer.putShort((short) 0);
		}

		byteBuffer.flip();
		byte[] bytes = new byte[byteBuffer.limit()];
		byteBuffer.get(bytes);
		return bytes;
	}

	@Override
	public void decode(ByteBuffer byteBuffer)
	{
		this.globalTransactionTimeout = byteBuffer.getInt();

		short length = byteBuffer.getShort();
		if (length > 0)
		{
			byte[] bytes = new byte[length];
			byteBuffer.get(bytes);
			this.setTransactionName(new String(bytes, UTF8));
		}
	}

	@Override
	public TransactionResponse handle(RpcContext rpcContext)
	{
		return transactionCoordinatorInboundHandler.handle(rpcContext, this);
	}
}
